import json
import re
import requests

class AbilitySuggestion():
    def __init__(self, position, ability_evalaute):
        self.position = position
        self.ability_evalaute = ability_evalaute
        self.message = []
        self.url = "https://api.siliconflow.cn/v1/chat/completions"
        self.payload = {
            "model": "Qwen/Qwen3-14B",
            "messages": self.message,
            "stream": False,
            "max_tokens": 4000,
            "min_p": 0.05,
            "stop": None,
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "response_format": {"type": "text"}
        }
        self.headers = {
            "Authorization": "Bearer sk-dgxjhtoohyyxvjzoouixerefxbwvwrtnenkejpkoxntxhiyg",
            "Content-Type": "application/json"
        }

    def get_ability_suggestion(self):
        self.message.append({
            'role': 'user',
            'content': (
                f'你是一个能力提升专家，面试者应聘的是{self.position}岗位。'
                f'面试者的六项能力评价如下：{self.ability_evalaute}。'
                f'请根据这些评价，给出针对性的提升建议，主语是"你"。'
                f'返回示例为{{"professional_knowledge_advice": "专业知识提升建议", "adaptability_advice": "应变抗压提升建议", "skill_match_advice": "技能提升建议", '
                f'"innovation_advice": "创新能力提升建议", "communication_advice": "语言表达能力提升建议", "logical_thinking_advice": "逻辑思维能力提升建议"}}'
            )
        })


        response = requests.request("POST", self.url, json=self.payload, headers=self.headers)
        # 解析JSON并提取content和code
        full_response = json.loads(response.text)
        # Step 2: 提取 content 字符串
        content = full_response["choices"][0]["message"]["content"]
        # Step 3: 从 content 中提取嵌套的 JSON 分数字符串（注意它是字符串，不是对象）
        match = re.search(r"\{.*?\}", content, re.DOTALL)
        if not match:
            raise ValueError("没有找到嵌套的评分 JSON")
        advice_json_str = match.group(0)
        # Step 4: 将嵌套的 JSON 字符串解析为 Python 字典
        advice_data = json.loads(advice_json_str)
        return advice_data